﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.EditWanderStateHelper;
using S.Common.helper;
using S.PurchaseAndSales.Api.Application.Command.SheepSaleCommand;
using S.PurchaseAndSales.Api.Dto;
using S.PurchaseAndSales.Domain.Dto;
using S.PurchaseAndSales.Domain.Model;
using S.PurchaseAndSales.Infrastructure.Interface.SalesForm;
using S.PurchaseAndSales.Read.Api.Dto;

namespace S.PurchaseAndSales.Api.Application.CommandHandlers.SheepSaleHandler
{
    public class SheepSaleBUpdateWorkStateCommandHandler : IRequestHandler<SheepSaleBUpdateWorkStateCommand, bool>
    {
        private readonly ISheepSaleRepository sheepSaleRepository;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;

        public SheepSaleBUpdateWorkStateCommandHandler(ISheepSaleRepository sheepSaleRepository, IMapper mapper, IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            this.sheepSaleRepository = sheepSaleRepository;
            this.mapper = mapper;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 批量修改羊只销售仓库状态
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(SheepSaleBUpdateWorkStateCommand request, CancellationToken cancellationToken)
        {
            
            SheepTransFersDto sheepTransFersDto=new SheepTransFersDto();
            foreach(var item in request.sheepSaleModels)
            {
                item.CheckState = 2;
                string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
                if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer"))
                {
                    authHeader = authHeader.Substring("Bearer ".Length).Trim();
                }
                string LocalConsul = configuration.GetValue<string>("GetKongaIp");

                SheepSaleModel sheepSaleModel = mapper.Map<SheepSaleModel>(item);
                //修改在场状态:
                EditReproductivePresenceState.UpdateReproductivePresenceState(item.EarTag, 2, 3, DateTime.Now, LocalConsul);
                //修改流转状态:
                EditWanderState.EditWander(item.EarTag, 7, LocalConsul);
                var aa = configuration["GetKongaIp"];
                SheepFileDto sheepFileDto = HttpClientHelper.GetResponse<SheepFileDto>(aa + "/ach/api/SheepFileModel/GetSheepFilesByEarTag?EarTag=" + item.EarTag);

                //转出栋舍
                //var House = FieldIdTransfer = GetField(sheepFileDto.ColumnName, configuration).value;
                //var HouseIdTransfer = GetHouse(sheepFileDto.BuildingName, configuration) == null:FieldIdTransfer = GetField(sheepFileDto.ColumnName, configuration).value=0;
                var HouseIdTransfer = 0;
                if (GetHouse(sheepFileDto.BuildingName, configuration)==null)
                {
                    HouseIdTransfer = 0;
                }
                else
                {
                    HouseIdTransfer = GetHouse(sheepFileDto.BuildingName, configuration).value;
                }
                    var FieldIdTransfer = 0;
                if (GetField(sheepFileDto.ColumnName, configuration) == null)
                {
                    FieldIdTransfer = 0;
                }
                else
                {
                    FieldIdTransfer = GetField(sheepFileDto.ColumnName, configuration).value;
                }
                sheep dto = new sheep()
                {
                    SheepRescissionId=0,
                    EarTag = item.EarTag,
                    SurrenderDate = DateTime.Now,
                    RoundType=16,
                    TurnOutBuild= HouseIdTransfer,
                    TurnOutHuts= FieldIdTransfer,
                    TurnOuBuildingManagementId = HouseIdTransfer,
                    TurnOuColumnManagementId= FieldIdTransfer,
                    ShiftToBuild=0,
                    ShiftToHuts=0,
                    ShiftToBuildingManagementId=0,
                    ShiftToColumnManagementId=0,
                    Variety=(int)sheepFileDto.Variety,
                    CreateBy=item.CreateBy,
                    CreateDate= DateTime.Now,
                    UpdateBy="",
                    UpdateDate= DateTime.Now,
                    IsDel=true,
                    DocumentNumbe=0,
                    Type=sheepFileDto.SheepTypeLabel,
                    Sex= sheepFileDto.Sex,
                    TransFerType=0
                };
                sheepTransFersDto.sheep.Add(dto);
            }
            var TranResult=SheepSheds(sheepTransFersDto, configuration);
            return await sheepSaleRepository.BatchUpdateMoneyState(request.sheepSaleModels);
        }
        /// <summary>
        /// 显示栋舍信息
        /// </summary>
        /// <returns></returns>
        private static HouseFieldDto GetHouse(string name, IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("GetKongaIp");
            return HttpClientHelper.GetResponseList<HouseFieldDto>(conf + "/Authorization/api/ColumnManagement/GetColumnList").FirstOrDefault(m => m.label == name);
        }
        /// <summary>
        /// 显示栏位信息
        /// </summary>
        /// <returns></returns>
        private static HouseFieldDto GetField(string name, IConfiguration configuration)
        {
            if (name == null)
            {
                return null;
            }
            else
            {
                var conf = configuration.GetValue<string>("GetKongaIp");
                return HttpClientHelper.GetResponseList<HouseFieldDto>(conf + "/Authorization/api/ColumnManagement/GetFieldMode").FirstOrDefault(m => m.label == name);
            }
        }
        /// <summary>
        /// 羊只批量转舍
        /// </summary>
        /// <returns></returns>
        private static string SheepSheds(SheepTransFersDto dto, IConfiguration configuration)
        {
            var conf = configuration.GetValue<string>("GetKongaIp");
            return HttpClientHelper.PostResponse(conf + "/transset/api/TransFer/CreateSheepTransFers", dto);
        }
    }
}
